﻿using CuttingEdge.Conditions;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using PSAMMatrixCloud.BLL.BizCommon;
using PSAMMatrixCloud.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace PSAMMatrixCloud.BLL.WebAPI
{
    /// <summary>
    /// 车道
    /// </summary>
    public class LaneDeviceAPIService
    {
        private string IP;
        public LaneDeviceAPIService(string ClientIP)
        {
            IP = ClientIP;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Add(string appID, string userID, string postData)
        {
            #region CheckParmeter

            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = Newtonsoft.Json.JsonConvert.DeserializeObject<LaneDeviceModel>(postData);//反序列化json对象
            Condition.Requires(modelRe.ParkingName, "exitname").IsNotNullOrWhiteSpace().IsNotLongerThan(100);
            Condition.Requires(modelRe.ParkingID, "parkingid").IsNotNullOrWhiteSpace().IsNotLongerThan(40);
            Condition.Requires(modelRe.ExitName, "exitname").IsNotNullOrWhiteSpace().IsNotLongerThan(50);
            Condition.Requires(modelRe.SignKey, "signkey").IsNotNullOrWhiteSpace().IsNotLongerThan(50);
            Condition.Requires<int?>(modelRe.Status, "status").IsNotNull().IsInRange(0,1);
            #endregion CheckParmeter

            #region Deal


            var model = new psam_deviceinfoModel();
            model.createip = IP;
            model.createtime = DateTime.Now;
            model.parkingid = modelRe.ParkingID;
            model.parkingname = modelRe.ParkingName;
            model.signkey = modelRe.SignKey;
            model.status = modelRe.Status;
            model.exitname = modelRe.ExitName;

            if (!new BLL.psam_deviceinfo().Add(model))
            {
                return SimpleResultHelper.SetDataExt(ErrorMsg.MsgSaveFail);
            }
            return SimpleResultHelper.SetDataForSuccess("", "成功");

            #endregion Deal
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Edit(string appID, string userID, string postData)
        {
            #region CheckParmeter

            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = Newtonsoft.Json.JsonConvert.DeserializeObject<LaneDeviceModel>(postData);//反序列化json对象
            Condition.Requires(modelRe.ParkingName, "exitname").IsNotNullOrWhiteSpace().IsNotLongerThan(100);
            Condition.Requires(modelRe.ParkingID, "parkingid").IsNotNullOrWhiteSpace().IsNotLongerThan(40);
            Condition.Requires(modelRe.ExitName, "exitname").IsNotNullOrWhiteSpace().IsNotLongerThan(50);
            Condition.Requires(modelRe.SignKey, "signkey").IsNotNullOrWhiteSpace().IsNotLongerThan(50);
            Condition.Requires<int?>(modelRe.Status, "status").IsNotNull().IsInRange(0, 1);
            Condition.Requires<int>(modelRe.ID, "id").IsInRange(1, int.MaxValue);
            #endregion CheckParmeter

            #region Deal
            var lane = new psam_deviceinfo();
            var model=lane.GetModel(modelRe.ID);
            model.modifyip = IP;
            model.modifytime = DateTime.Now;
            model.parkingid = modelRe.ParkingID;
            model.parkingname = modelRe.ParkingName;
            model.signkey = modelRe.SignKey;
            model.status = modelRe.Status;
            model.exitname = modelRe.ExitName;
            if (!lane.Update(model))
            {
                return SimpleResultHelper.SetDataExt(ErrorMsg.MsgSaveFail);
            }
            return SimpleResultHelper.SetDataForSuccess("", "成功");

            #endregion Deal
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Del(string appID, string userID, string postData)
        {
            #region CheckParmeter

            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = Newtonsoft.Json.JsonConvert.DeserializeObject<LaneDeviceModel>(postData);//反序列化json对象
            Condition.Requires<int>(modelRe.ID, "id").IsInRange(1, int.MaxValue);

            #endregion CheckParmeter

            #region Deal
            var lane = new psam_deviceinfo();
            var model = lane.GetModel(modelRe.ID);
            if (model == null)
            {
                return SimpleResultHelper.SetData(ErrorMsg.MsgInvalidLaneID, "车道id不存在");
            }
            else
            {
                if (!new psam_deviceinfo().Delete(modelRe.ID))
                {
                    return SimpleResultHelper.SetDataExt(ErrorMsg.MsgSaveFail);
                }
            }

            return SimpleResultHelper.SetDataForSuccess("", "成功");

            #endregion Deal
        }

        /// <summary>
        /// 查询车道记录(分页)
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Search(string appID, string userID, string postData)
        {
            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = JsonConvert.DeserializeObject<LaneDeviceSearchModel>(postData);//反序列化json对象
            Condition.Requires<int>(modelRe.pagesize, "pagesize").IsInRange(1, 100);
            if (modelRe.Status != null)
            {
                Condition.Requires<int?>(modelRe.Status, "status").IsInRange(0, 1);
            }
            #region Deal

            string strWhere = "1=1 ";
            if (modelRe.ID != null)
            {
                strWhere += " and id='{0}'";
                strWhere = string.Format(strWhere, modelRe.ID);
            }

            if (!string.IsNullOrWhiteSpace(modelRe.ParkingID))
            {
                strWhere += " and parkingid='{0}'";
                strWhere = string.Format(strWhere, modelRe.ParkingID);
            }

            if (!string.IsNullOrWhiteSpace(modelRe.ParkingName))
            {
                strWhere += " and parkingname='{0}'";
                strWhere = string.Format(strWhere, modelRe.ParkingName);
            }

            if (!string.IsNullOrWhiteSpace(modelRe.ExitName))
            {
                strWhere += " and exitname='{0}'";
                strWhere = string.Format(strWhere, modelRe.ExitName);
            }

            if (modelRe.Status!=null)
            {
                strWhere += " and status='{0}'";
                strWhere = string.Format(strWhere, modelRe.Status);
            }

            
            if (modelRe.CreateTime1 != null)
            {
                strWhere += " and createtime >= '{0}'";
                strWhere = string.Format(strWhere, modelRe.CreateTime1.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            if (modelRe.CreateTime2 != null)
            {
                strWhere += " and createtime <= '{0}'";
                strWhere = string.Format(strWhere, modelRe.CreateTime2.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            var bizLane = new psam_deviceinfo();
            
            var result = new Model.Entity.baseresponse<LaneDeviceResponseModel>();
            int total = bizLane.GetRecordCount(strWhere);
            if (total <= 0)
            {
                return SimpleResultHelper.SetDataForSuccess(result, "无数据");
            }
            result.total = total;

            DataSet dst = null;
            if (modelRe.pageindex <= 0 || modelRe.pagesize > 100)
            {
                dst = bizLane.GetList(strWhere);
            }
            else
            {
                dst = bizLane.GetListByPage(strWhere, " createtime desc ", modelRe.pagesize, modelRe.pageindex);
            }

            List<psam_deviceinfoModel> listEntry = bizLane.DataTableToList(dst.Tables[0]);
            for (int i = 0; i < listEntry.Count; i++)
            {
                var model = listEntry[i];
                result.rows.Add(new LaneDeviceResponseModel()
                {
                    CreateIP = model.createip,
                    CreateTime = model.createtime,
                    ExitName = model.exitname,
                    ID = model.id,
                    ModifyIP = model.modifyip,
                    ModifyTime = model.modifytime,
                    ParkingID = model.parkingid,
                    ParkingName = model.parkingname,
                    SignKey = model.signkey,
                    Status = model.status

                });
            }

            return SimpleResultHelper.SetDataForSuccess(result, "成功");

            #endregion Deal
        }
        #region 发送邮件
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Email(string appID, string userID, string postData)
        {
            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            SendEmailModel modelsend = JsonConvert.DeserializeObject<SendEmailModel>(postData);//反序列化json对象

            //验证参数合法性
            //Condition.Requires(modelsend.email, "email").IsNotNullOrWhiteSpace();

            #region Deal
            var emailAcount = Model.EMailConfigModel.MailAuthUser;
            var emailPassword = Model.EMailConfigModel.MailAuthPass;
            var MailServer = Model.EMailConfigModel.MailServer;
            MailMessage mailObj = new MailMessage();
            mailObj.From = new MailAddress(emailAcount); //发送人邮箱地址  
            for (var i = 0; i < modelsend.email.Length; i++)
            {
                mailObj.To.Add(modelsend.email[i]);  //收件人邮箱地址
            }
            mailObj.CC.Add("yuanjp@genvict.com");
            mailObj.Subject = modelsend.theme;  //主题
            mailObj.Body = modelsend.emaildata;  //正文,
            mailObj.IsBodyHtml = true; //表示正文内容是HTML

            SmtpClient smtp = new SmtpClient();
            smtp.Host = MailServer;     //smtp服务器名称
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = new NetworkCredential(emailAcount, emailPassword); //发送人的登录名和密码
            smtp.Send(mailObj);

            return SimpleResultHelper.SetDataForSuccess(null, "发送成功");

            #endregion Deal
        }
#endregion API
    }
}
